<template>
  <div class="myExcel">
    <el-card class="mycard">
      <h4>员工导入</h4>
      <el-alert
        title="每次导入仅可添加1000名员工，姓名、手机、入职时间、聘用形式为必填项"
        type="warning"
        show-icon
      >
      </el-alert>
      <myexcel :beforeUpload="beforeUpload" :onSuccess="onSuccess"></myexcel>
    </el-card>
  </div>
</template>

<script>
import {importEptApi} from '@/api/employees'
import moment from 'moment'
export default {
  name: 'myExcel',
  methods: {
    //将Excel日期改为正常日期
    formatDate(day){
      const timestamp = (day-1) * 60 * 60 * 24 * 1000
      const time = new Date(timestamp)
       time.setFullYear(time.getFullYear()-70) 
       return time
    },
    //上传时触发
    beforeUpload (file) {
      console.log(file)
      let isLess2M = file.size / 1024 / 1024 < 2
      if (!isLess2M) {
        this.$message.error('上传文件大小不能大于2Mb')
      }
      return isLess2M
    },
    //上传成功触发
    async onSuccess ({ header, results }) {
      console.log(header)
      console.log(results)
      let obj = {
        手机号: 'mobile',
        姓名: 'username',
        入职日期: 'timeOfEntry',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门:'departmentName',
        聘用形式:'formOfEmployment'

      }
      const res = results.map(item=>{
        const newObj = {}
        Object.keys(item).forEach(key=>{
          //将时间转换为正常时间 ，格式为yyyy-mm-dd
          if(obj[key] == 'timeOfEntry' || obj[key] == 'correctionTime'){
             newObj[obj[key]] = moment(this.formatDate(item[key])).format('YYYY-MM-DD')
          }else{
            newObj[obj[key]]=item[key]
          }
          
        })
        return newObj
      })
      console.log(res);
      let result = await importEptApi(res)
      console.log(result);
      this.$message.success('导入员工成功')
      this.$router.push('/employees')
    }

  }
}
</script>

<style lang="scss">
.myExcel {
  .mycard {
    height: 800px;
    margin: 20px;
    h4 {
      text-align: center;
    }
  }
}
</style>
